<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书单列表 - ZLibLike平台</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div th:replace="~{commons/header :: header}"></div>
    
    <div class="container mt-4">
        <div class="row mb-4">
            <div class="col-md-6">
                <h2>书单列表</h2>
            </div>
            <div class="col-md-6 text-right">
                <button id="createBookList" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 创建新书单
                </button>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <ul class="nav nav-tabs card-header-tabs" id="bookListTabs" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link active" id="public-tab" data-toggle="tab" href="#public" role="tab">
                                    公开书单
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="my-tab" data-toggle="tab" href="#my" role="tab">
                                    我的书单
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="card-body">
                        <div class="tab-content" id="bookListTabContent">
                            <!-- 公开书单 -->
                            <div class="tab-pane fade show active" id="public" role="tabpanel">
                                <div class="form-group">
                                    <div class="input-group">
                                        <input type="text" id="publicSearchInput" class="form-control" placeholder="搜索公开书单...">
                                        <div class="input-group-append">
                                            <button id="publicSearchBtn" class="btn btn-outline-secondary">
                                                <i class="bi bi-search"></i> 搜索
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="publicBookLists" class="row">
                                    <!-- 公开书单将通过JavaScript加载 -->
                                    <div class="col-12 text-center py-5">
                                        <div class="spinner-border" role="status">
                                            <span class="sr-only">加载中...</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="publicPagination" class="d-flex justify-content-center mt-4">
                                    <!-- 分页控件将通过JavaScript加载 -->
                                </div>
                            </div>
                            
                            <!-- 我的书单 -->
                            <div class="tab-pane fade" id="my" role="tabpanel">
                                <div class="form-group">
                                    <div class="input-group">
                                        <input type="text" id="mySearchInput" class="form-control" placeholder="搜索我的书单...">
                                        <div class="input-group-append">
                                            <button id="mySearchBtn" class="btn btn-outline-secondary">
                                                <i class="bi bi-search"></i> 搜索
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="myBookLists" class="row">
                                    <!-- 我的书单将通过JavaScript加载 -->
                                    <div class="col-12 text-center py-5">
                                        <div class="spinner-border" role="status">
                                            <span class="sr-only">加载中...</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="myPagination" class="d-flex justify-content-center mt-4">
                                    <!-- 分页控件将通过JavaScript加载 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 创建书单模态框 -->
    <div class="modal fade" id="createBookListModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">创建新书单</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="createErrorMessage" class="alert alert-danger d-none" role="alert"></div>
                    
                    <form id="createBookListForm">
                        <div class="form-group">
                            <label for="createTitle">书单标题 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="createTitle" required maxlength="100">
                        </div>
                        
                        <div class="form-group">
                            <label for="createDescription">书单描述</label>
                            <textarea class="form-control" id="createDescription" rows="3" maxlength="500" placeholder="介绍一下这个书单的主题或内容..."></textarea>
                            <small class="form-text text-muted">最多500个字符</small>
                        </div>
                        
                        <div class="form-group">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="createIsPublic" checked>
                                <label class="custom-control-label" for="createIsPublic">公开书单（所有用户可见）</label>
                            </div>
                            <small class="form-text text-muted">私人书单只有您自己可以查看</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitCreateBookList">创建</button>
                </div>
            </div>
        </div>
    </div>
    
    <div th:replace="~{commons/footer :: footer}"></div>
    
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        $(document).ready(function() {
            // 当前页码
            let publicCurrentPage = 1;
            let myCurrentPage = 1;
            const pageSize = 12;
            
            // 加载初始数据
            loadPublicBookLists();
            
            // 选项卡切换事件
            $('#bookListTabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if (e.target.id === 'my-tab') {
                    loadMyBookLists();
                } else {
                    loadPublicBookLists();
                }
            });
            
            // 绑定创建书单按钮点击事件
            $('#createBookList').click(function() {
                $('#createBookListModal').modal('show');
            });
            
            // 绑定搜索按钮点击事件
            $('#publicSearchBtn').click(function() {
                publicCurrentPage = 1;
                loadPublicBookLists();
            });
            
            $('#mySearchBtn').click(function() {
                myCurrentPage = 1;
                loadMyBookLists();
            });
            
            // 回车键触发搜索
            $('#publicSearchInput').keypress(function(e) {
                if (e.which === 13) {
                    publicCurrentPage = 1;
                    loadPublicBookLists();
                }
            });
            
            $('#mySearchInput').keypress(function(e) {
                if (e.which === 13) {
                    myCurrentPage = 1;
                    loadMyBookLists();
                }
            });
            
            // 绑定创建书单表单提交事件
            $('#submitCreateBookList').click(function() {
                createBookList();
            });
            
            // 加载公开书单
            function loadPublicBookLists() {
                const keyword = $('#publicSearchInput').val().trim();
                const url = `/api/book-lists/public?page=${publicCurrentPage}&size=${pageSize}${keyword ? '&keyword=' + encodeURIComponent(keyword) : ''}`;
                
                $('#publicBookLists').html(`
                    <div class="col-12 text-center py-5">
                        <div class="spinner-border" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                    </div>
                `);
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            renderBookLists(data.data, 'public');
                        } else {
                            $('#publicBookLists').html(`
                                <div class="col-12 text-center py-5">
                                    <p class="text-muted">加载失败: ${data.message || '未知错误'}</p>
                                </div>
                            `);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        $('#publicBookLists').html(`
                            <div class="col-12 text-center py-5">
                                <p class="text-muted">加载失败，请稍后重试</p>
                            </div>
                        `);
                    });
            }
            
            // 加载我的书单
            function loadMyBookLists() {
                const keyword = $('#mySearchInput').val().trim();
                const url = `/api/book-lists/my?page=${myCurrentPage}&size=${pageSize}${keyword ? '&keyword=' + encodeURIComponent(keyword) : ''}`;
                
                $('#myBookLists').html(`
                    <div class="col-12 text-center py-5">
                        <div class="spinner-border" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                    </div>
                `);
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            renderBookLists(data.data, 'my');
                        } else {
                            $('#myBookLists').html(`
                                <div class="col-12 text-center py-5">
                                    <p class="text-muted">加载失败: ${data.message || '未知错误'}</p>
                                </div>
                            `);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        $('#myBookLists').html(`
                            <div class="col-12 text-center py-5">
                                <p class="text-muted">加载失败，请稍后重试</p>
                            </div>
                        `);
                    });
            }
            
            // 渲染书单列表
            function renderBookLists(data, type) {
                const container = type === 'public' ? $('#publicBookLists') : $('#myBookLists');
                const paginationContainer = type === 'public' ? $('#publicPagination') : $('#myPagination');
                const bookLists = data.content;
                const totalPages = data.totalPages;
                
                if (bookLists.length === 0) {
                    container.html(`
                        <div class="col-12 text-center py-5">
                            <p class="text-muted">暂无书单</p>
                        </div>
                    `);
                    paginationContainer.html('');
                    return;
                }
                
                let html = '';
                
                bookLists.forEach(bookList => {
                    html += `
                        <div class="col-md-4 mb-4">
                            <div class="card h-100">
                                <div class="card-body">
                                    <h5 class="card-title">
                                        <a href="/book-list-detail.html?id=${bookList.id}" class="text-decoration-none">
                                            ${bookList.title}
                                        </a>
                                    </h5>
                                    <h6 class="card-subtitle mb-2 text-muted">by ${bookList.creatorName}</h6>
                                    <p class="card-text text-truncate">${bookList.description || '暂无描述'}</p>
                                </div>
                                <div class="card-footer text-muted">
                                    <small>
                                        <i class="bi bi-book"></i> ${bookList.bookCount} 本书 
                                        <span class="mx-2">•</span>
                                        <i class="bi bi-calendar"></i> ${new Date(bookList.createTime).toLocaleDateString()}
                                    </small>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                container.html(html);
                
                // 渲染分页
                renderPagination(totalPages, type === 'public' ? publicCurrentPage : myCurrentPage, type);
            }
            
            // 渲染分页
            function renderPagination(totalPages, currentPage, type) {
                const container = type === 'public' ? $('#publicPagination') : $('#myPagination');
                
                if (totalPages <= 1) {
                    container.html('');
                    return;
                }
                
                let html = `
                    <nav>
                        <ul class="pagination">
                            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" data-page="${currentPage - 1}" aria-label="上一页">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                `;
                
                const maxPages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxPages / 2));
                let endPage = Math.min(totalPages, startPage + maxPages - 1);
                
                if (endPage - startPage + 1 < maxPages) {
                    startPage = Math.max(1, endPage - maxPages + 1);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    html += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `;
                }
                
                html += `
                            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                                <a class="page-link" href="#" data-page="${currentPage + 1}" aria-label="下一页">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                `;
                
                container.html(html);
                
                // 绑定分页点击事件
                container.find('.page-link').click(function(e) {
                    e.preventDefault();
                    const page = parseInt($(this).data('page'));
                    
                    if (type === 'public') {
                        publicCurrentPage = page;
                        loadPublicBookLists();
                    } else {
                        myCurrentPage = page;
                        loadMyBookLists();
                    }
                });
            }
            
            // 创建书单
            function createBookList() {
                // 表单验证
                const title = $('#createTitle').val().trim();
                if (!title) {
                    $('#createErrorMessage').text('书单标题不能为空').removeClass('d-none');
                    return;
                }
                
                // 准备数据
                const bookListData = {
                    title: title,
                    description: $('#createDescription').val().trim(),
                    isPublic: $('#createIsPublic').is(':checked')
                };
                
                // 发送请求
                fetch('/api/book-lists', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(bookListData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        // 创建成功，跳转到详情页
                        window.location.href = `/book-list-detail.html?id=${data.data.id}`;
                    } else {
                        // 显示错误信息
                        $('#createErrorMessage').text(data.message || '创建失败，请稍后重试').removeClass('d-none');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#createErrorMessage').text('创建过程中发生错误，请稍后重试').removeClass('d-none');
                });
            }
        });
    </script>
</body>
</html> 